package jt.com.jt809.init;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import jt.com.jt809.config.NettyConfig;
import jt.com.jt809.handler.inbound.MessageForwardInboundHandler;
import jt.com.jt809.handler.inbound.ServerByte2MessageInboundHandler;
import jt.com.jt809.handler.outbound.Message2ByteOutboundHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Netty 服务端处理流程配置
 *
 * @Author OuJiaJun
 * @Date 2024/4/24 14:26
 */
@Component
public class JT809ServerChannelInit extends ChannelInitializer<SocketChannel> {
    @Resource
    private NettyConfig.NettyServerConfig serverConfig;
    @Resource
    private ServerByte2MessageInboundHandler serverByte2MessageInboundHandler;
    @Resource
    private MessageForwardInboundHandler messageForwardInboundHandler;
    @Resource
    private Message2ByteOutboundHandler message2ByteOutboundHandler;

    @Override
    public void initChannel(SocketChannel socketChannel) throws Exception {
        // 用于处理连接空闲状态的组件，根据配置的读、写和全部空闲时间进行超时判断
        socketChannel.pipeline().addLast(new IdleStateHandler(serverConfig.getReaderIdleTimeSeconds(), serverConfig.getWriterIdleTimeSeconds(), serverConfig.getAllIdleTimeSeconds(), TimeUnit.SECONDS));
        // 将消息对象转换为字节码的出站处理器。
        socketChannel.pipeline().addLast(message2ByteOutboundHandler);
        // 将接收到的字节码转换为消息对象的入站处理器
        socketChannel.pipeline().addLast(serverByte2MessageInboundHandler);
        // 消息转发的入站处理器，用于将处理后的消息转发给其他处理组件或存储。
        socketChannel.pipeline().addLast(messageForwardInboundHandler);
    }
}
